package com.zzp.fastdfs.file.utils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 佐斯特勒
 * <p>
 *  人皆知有用之用，而莫知无用之用也
 * </p>
 * @version v1.0.0
 * @date 2020/1/28 20:13
 * @see  UserAgentUtils
 **/
public class UserAgentUtils {

    /**
     * 获取用户代理对象（请请求头中）
     *
     * @param req 请求{@link HttpServletRequest}
     * @return 代理对象 {@link UserAgent}
     */
    public static UserAgent getUserAgent(HttpServletRequest req) {
        return UserAgent.parseUserAgentString(req.getHeader("User-Agent"));
    }

    /**
     * 获取用户浏览器
     *
     * @param req 请求{@link HttpServletRequest}
     * @return 浏览器对象 {@link Browser}
     */
    public static Browser getBrowser(HttpServletRequest req) {
        return getUserAgent(req).getBrowser();
    }

    /**
     * 获取用户的 IP 地址
     *
     * @param req {@link HttpServletRequest}
     * @return {@code String} 用户 IP 地址
     */
    public static String getIpAddr(HttpServletRequest req) {
        // 获取表示 HTTP 请求端真实的IP
        /*
         * 层层递进一步一步获取最终的地址
         */
        var ip = req.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = req.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
